package com.movitech.mobile.cz.base.impl;

import com.google.common.collect.Lists;
import com.movitech.mobile.cz.base.common.util.CommonConstants;
import com.movitech.mobile.cz.base.common.util.NumberUtils;
import com.movitech.mobile.cz.base.common.util.PageCode;
import com.movitech.mobile.cz.base.common.util.excel.ExportExcel;
import com.movitech.mobile.cz.base.entity.*;
import com.movitech.mobile.cz.base.mapper.SpecialPurchaseReportMapper;
import com.movitech.mobile.cz.base.modules.config.PurchasePlanFlowTypeEnum;
import com.movitech.mobile.cz.base.modules.controller.RestReturnResult;
import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 专项采购模块Service
 * @author Jack.Gong
 * @since 2018-05-24
 *
 */
@Service("specialPurchaseReportService")
@Transactional
public class SpecialPurchaseReportService {

	private Logger logger = Logger.getLogger(SpecialPurchaseReportService.class);
    @Autowired
    private SpecialPurchaseReportMapper specialPurchaseReportMapper;

    public PageCode searchStrategicPurchaseDetail(STDetailSearchReqVO reqVO){
		try{

			PageCode pageCode = new PageCode(reqVO.getPageNumber(), reqVO.getPageSize());
			Map<String, Object> map = new HashMap<String, Object>();

			map.put("categoryId", reqVO.getCategoryId());
			map.put("supplierName", reqVO.getSupplierName());
			map.put("purchaseStartTime", reqVO.getPurchaseStartTime());
			map.put("purchaseEndTime", reqVO.getPurchaseEndTime());

			pageCode.setCount(specialPurchaseReportMapper.searchStrategicPurchaseDetailCount(map));

			map.put("currentRecordNum", (pageCode.getPageNo() - 1) * pageCode.getPageSize());
			map.put("pageSize", pageCode.getPageSize());
			map.put("pageFlag", reqVO.getPageFlag());

			List<STDetailSearchResVO>  data = specialPurchaseReportMapper.searchStrategicPurchaseDetail(map);
			List<STDetailSearchResVO> list = Lists.newArrayList();
			STDetailSearchResVO resTem = null;
			Double price = 0d;
			int i=0;
			for(STDetailSearchResVO stDetailSearchResVO:data){
				i++;
				String key = stDetailSearchResVO.getCategoryName()+stDetailSearchResVO.getSuppliersName();
				if(resTem==null){
					resTem = stDetailSearchResVO;
					price+=stDetailSearchResVO.getFinalInterviewWithTax();
					list.add(stDetailSearchResVO);
				}else{
					String keyTem = resTem.getCategoryName()+resTem.getSuppliersName();
					if(!key.equals(keyTem)){
						STDetailSearchResVO total = new STDetailSearchResVO();
						BeanUtils.copyProperties(resTem,total);
						total.setRegionalCompanyName("合计");
						total.setFinalInterviewWithTax(price);
						list.add(total);
						list.add(stDetailSearchResVO);
						price = stDetailSearchResVO.getFinalInterviewWithTax();
					}else{
						price+=stDetailSearchResVO.getFinalInterviewWithTax();
						list.add(stDetailSearchResVO);
					}
				}
				if(i==data.size()){
					STDetailSearchResVO total = new STDetailSearchResVO();
					BeanUtils.copyProperties(resTem,total);
					total.setRegionalCompanyName("合计");
					total.setFinalInterviewWithTax(price);
					list.add(total);
				}
			}
			pageCode.setList(list);
			return pageCode;
		}catch(Exception e){
			e.printStackTrace();
			logger.error("==============searchSpecialPurchaseDetail======e:===="+e.getMessage());
			throw new RuntimeException(e.getMessage(), e.getCause());
		}
	}

	public RestReturnResult searchSpecialPurchaseDetail(SPDetailSearchReqVO reqVO) {
		RestReturnResult restReturnResult = RestReturnResult.success();
		
		try{
			
			PageCode pageCode = new PageCode(reqVO.getPageNumber(), reqVO.getPageSize());
			Map<String, Object> map = new HashMap<String, Object>();
			
			map.put("regionalCompanyId", reqVO.getRegionalCompanyId());
			map.put("purchaseStartTime", reqVO.getPurchaseStartTime());
			map.put("purchaseEndTime", reqVO.getPurchaseEndTime());
			
			pageCode.setCount(specialPurchaseReportMapper.searchSpecialPurchaseDetailCount(map));
			
			map.put("currentRecordNum", (pageCode.getPageNo() - 1) * pageCode.getPageSize());
            map.put("pageSize", pageCode.getPageSize());
            map.put("pageFlag", reqVO.getPageFlag());
            
            List<SPDetailSearchResVO>  list = specialPurchaseReportMapper.searchSpecialPurchaseDetail(map);
            pageCode.setList(list);
            
            return new RestReturnResult(CommonConstants.SUCCESS, pageCode);
			
		}catch(Exception e){
			e.printStackTrace();
			logger.error("==============searchSpecialPurchaseDetail======e:===="+e.getMessage());
			throw new RuntimeException(e.getMessage(), e.getCause());
		}
		
	}

	public void exportSpecialPurchaseDetail(SPDetailSearchReqVO reqVO, HttpServletResponse response, HttpServletRequest request) {
		
		try{
			
			String fileName = "专项采购详情统计.xlsx";
			
			Map<String, Object> map = new HashMap<String, Object>();
			
			map.put("regionalCompanyId", reqVO.getRegionalCompanyId());
			map.put("purchaseStartTime", reqVO.getPurchaseStartTime());
			map.put("purchaseEndTime", reqVO.getPurchaseEndTime());
			
			new ExportExcel("专项采购详情统计", SPDetailSearchResVO.class).setDataList(specialPurchaseReportMapper.searchSpecialPurchaseDetail(map))
            .write(request,response, fileName).dispose();
			
		}catch(Exception e){
			e.printStackTrace();
			logger.error("==============exportSpecialPurchaseDetail======e:===="+e.getMessage());
			throw new RuntimeException(e.getMessage(), e.getCause());
		}
		
	}

    public List<GroupPurchaseTypeVO>  groupPurchaseType(PurchaseReportReqVO purchaseTypeReqVO){
		List<GroupPurchaseTypeVO> ls=specialPurchaseReportMapper.groupPurchaseTypeSummary(purchaseTypeReqVO);
//		GroupPurchaseTypeRspVO groupPurchaseTypeRspVO=new GroupPurchaseTypeRspVO();
		GroupPurchaseTypeVO totalGroupPurchaseTypeVO=new GroupPurchaseTypeVO();
		totalGroupPurchaseTypeVO.setPurchaseTypeName("合计");
		totalGroupPurchaseTypeVO.setPurchaseAmountPercent("100.00%");
		totalGroupPurchaseTypeVO.setPurchaseMoneyPercent("100.00%");
//		totalGroupPurchaseTypeVO.setPurchaseStartTime(purchaseTypeReqVO.getPurchaseStartTime());
//		totalGroupPurchaseTypeVO.setPurchaseEndTime(purchaseTypeReqVO.getPurchaseEndTime());
		Integer purchaseAmountTotal=0;
		Double purchaseMoneyTotal=0.0;
		for(GroupPurchaseTypeVO obj:ls){
			obj.setPurchaseTypeName(PurchasePlanFlowTypeEnum.getNameByKey(Integer.valueOf(obj.getPurchaseType())));
			obj.setPurchaseStartTime(purchaseTypeReqVO.getPurchaseStartTime());
			obj.setPurchaseEndTime(purchaseTypeReqVO.getPurchaseEndTime());
			purchaseMoneyTotal=purchaseMoneyTotal+obj.getPurchaseMoney();
			purchaseAmountTotal=purchaseAmountTotal+obj.getPurchaseAmount();
		}
		totalGroupPurchaseTypeVO.setPurchaseAmount(purchaseAmountTotal);
		totalGroupPurchaseTypeVO.setPurchaseMoney(NumberUtils.seekercentage2Double(purchaseMoneyTotal));
		for(GroupPurchaseTypeVO obj:ls){
			obj.setPurchaseAmountPercent(accuracy(obj.getPurchaseAmount(),purchaseAmountTotal));
			obj.setPurchaseMoneyPercent(accuracy(obj.getPurchaseMoney(),purchaseMoneyTotal));
		}
		ls.add(totalGroupPurchaseTypeVO);
//		groupPurchaseTypeRspVO.setLstGroupPurchaseTypeVO(ls);
//		groupPurchaseTypeRspVO.setGroupPurchaseTypeVO(totalGroupPurchaseTypeVO);
		return ls;
    }

	public List<GroupPurchaseAmountVO>  groupPurchaseAmount(PurchaseReportReqVO purchaseTypeReqVO){
//		GroupPurchaseAmountRspVO groupPurchaseAmountRspVO=new GroupPurchaseAmountRspVO();
		List<GroupPurchaseAmountVO> ls=specialPurchaseReportMapper.groupPurchaseAmountSummaryNew(purchaseTypeReqVO);
		GroupPurchaseAmountVO groupPurchaseAmountVO=new GroupPurchaseAmountVO();
		groupPurchaseAmountVO.setPurchaseBodyName("合计");
		groupPurchaseAmountVO.setPurchaseAmountPercent("100.00%");
		groupPurchaseAmountVO.setPurchaseMoneyPercent("100.00%");
//		groupPurchaseAmountVO.setPurchaseStartTime(purchaseTypeReqVO.getPurchaseStartTime());
//		groupPurchaseAmountVO.setPurchaseEndTime(purchaseTypeReqVO.getPurchaseEndTime());
		Integer purchaseAmountTotal=0;
		Double purchaseMoneyTotal=0.0;
		for(GroupPurchaseAmountVO obj:ls){
			if(obj.getPurchaseBody()!=null&&"2".equals(obj.getPurchaseBody())){
				obj.setPurchaseBodyName("集团");
			}else{
				obj.setPurchaseBodyName("地区公司");
			}
			obj.setPurchaseStartTime(purchaseTypeReqVO.getPurchaseStartTime());
			obj.setPurchaseEndTime(purchaseTypeReqVO.getPurchaseEndTime());
			purchaseMoneyTotal=purchaseMoneyTotal+obj.getPurchaseMoney();
			purchaseAmountTotal=purchaseAmountTotal+obj.getPurchaseAmount();
		}
		groupPurchaseAmountVO.setPurchaseAmount(purchaseAmountTotal);
		groupPurchaseAmountVO.setPurchaseMoney(NumberUtils.seekercentage2Double(purchaseMoneyTotal));
		for(GroupPurchaseAmountVO obj:ls){
			obj.setPurchaseAmountPercent(accuracy(obj.getPurchaseAmount(),purchaseAmountTotal));
			obj.setPurchaseMoneyPercent(accuracy(obj.getPurchaseMoney(),purchaseMoneyTotal));
		}
		ls.add(groupPurchaseAmountVO);
//		groupPurchaseAmountRspVO.setGroupPurchaseAmountVO(groupPurchaseAmountVO);
//		groupPurchaseAmountRspVO.setLstGroupPurchaseAmountVO(ls);
		return ls;
	}

	public List<AreaPurchaseAmountVO>  areaPurchaseAmount(PurchaseReportReqVO purchaseTypeReqVO){
		List<AreaPurchaseAmountVO> ls=specialPurchaseReportMapper.areaPurchaseAmountSummary(purchaseTypeReqVO);
		return ls;
	}

	public RestReturnResult searchSpecialPurchaseAbortive(SPAbortiveSearchReqVO reqVO) {
		RestReturnResult restReturnResult = RestReturnResult.success();
		
		try{
			
			PageCode pageCode = new PageCode(reqVO.getPageNumber(), reqVO.getPageSize());
			Map<String, Object> map = new HashMap<String, Object>();
			
			map.put("regionalCompanyId", reqVO.getRegionalCompanyId());
			map.put("abortiveStartTime", reqVO.getAbortiveStartTime());
			map.put("abortiveEndTime", reqVO.getAbortiveEndTime());
			
			pageCode.setCount(specialPurchaseReportMapper.searchSpecialPurchaseAbortiveCount(map));
			
			map.put("currentRecordNum", (pageCode.getPageNo() - 1) * pageCode.getPageSize());
            map.put("pageSize", pageCode.getPageSize());
            map.put("pageFlag", reqVO.getPageFlag());
            
            List<SPAbortiveSearchResVO>  list = specialPurchaseReportMapper.searchSpecialPurchaseAbortive(map);
            pageCode.setList(list);
            
            return new RestReturnResult(CommonConstants.SUCCESS, pageCode);
			
		}catch(Exception e){
			e.printStackTrace();
			logger.error("==============searchSpecialPurchaseAbortive======e:===="+e.getMessage());
			throw new RuntimeException(e.getMessage(), e.getCause());
		}
		
	}

	public void exportSpecialPurchaseAbortive(SPAbortiveSearchReqVO reqVO, HttpServletResponse response, HttpServletRequest request) {
		
		try{
			
			String fileName = "专项采购流标统计.xlsx";
			
			Map<String, Object> map = new HashMap<String, Object>();
			
			map.put("regionalCompanyId", reqVO.getRegionalCompanyId());
			map.put("abortiveStartTime", reqVO.getAbortiveStartTime());
			map.put("abortiveEndTime", reqVO.getAbortiveEndTime());
			
			new ExportExcel("专项采购流标统计", SPAbortiveSearchResVO.class).setDataList(specialPurchaseReportMapper.searchSpecialPurchaseAbortive(map))
            .write(request,response, fileName).dispose();
			
		}catch(Exception e){
			e.printStackTrace();
			logger.error("==============exportSpecialPurchaseAbortive======e:===="+e.getMessage());
			throw new RuntimeException(e.getMessage(), e.getCause());
		}
		
	}

	public  String accuracy(double num, double total){
		DecimalFormat df = new DecimalFormat("0.00");
		if(total==0.0||num== 0){
			return "0.00%";
		}else{
			double accuracy_num = num / total * 100;
			return df.format(accuracy_num)+"%";
		}
	}

	public List<AreaPurchaseTypeVO>  areaPurchaseType(PurchaseReportReqVO purchaseTypeReqVO){
		List<AreaPurchaseTypeVO> ls=specialPurchaseReportMapper.areaPurchaseTypeSummary(purchaseTypeReqVO);
		if(ls==null||ls.size()==0)return null;
		List<AreaPurchaseTypeVO> lsCopy=new ArrayList<>();
		String regionalCompanyId=ls.get(0).getRegionalCompanyId();
		Integer purchaseAmount=ls.get(0).getPurchaseAmount();
		Double purchaseMoney=ls.get(0).getPurchaseMoney();
		ls.get(0).setPurchaseTypeName(PurchasePlanFlowTypeEnum.getNameByKey(Integer.valueOf(ls.get(0).getPurchaseType())));
		ls.get(0).setPurchaseStartTime(purchaseTypeReqVO.getPurchaseStartTime());
		ls.get(0).setPurchaseEndTime(purchaseTypeReqVO.getPurchaseEndTime());
		lsCopy.add(ls.get(0));
		for(int i=1;i<ls.size();i++){
			if((regionalCompanyId+"").equals((ls.get(i).getRegionalCompanyId())+"")){
				purchaseAmount=purchaseAmount+ls.get(i).getPurchaseAmount();
				purchaseMoney=purchaseMoney+ls.get(i).getPurchaseMoney();
			}else{
				AreaPurchaseTypeVO areaPurchaseTypeVO=new AreaPurchaseTypeVO();
				areaPurchaseTypeVO.setPurchaseTypeName("合计");
				areaPurchaseTypeVO.setPurchaseStartTime(purchaseTypeReqVO.getPurchaseStartTime());
				areaPurchaseTypeVO.setPurchaseEndTime(purchaseTypeReqVO.getPurchaseEndTime());
				areaPurchaseTypeVO.setPurchaseAmount(purchaseAmount);
				areaPurchaseTypeVO.setPurchaseMoney(NumberUtils.seekercentage2Double(purchaseMoney));
				areaPurchaseTypeVO.setRegionalCompanyId(ls.get(i-1).getRegionalCompanyId());
				areaPurchaseTypeVO.setRegionalCompanyName(ls.get(i-1).getRegionalCompanyName());
				lsCopy.add(areaPurchaseTypeVO);

				regionalCompanyId=ls.get(i).getRegionalCompanyId();
				purchaseAmount=ls.get(i).getPurchaseAmount();
				purchaseMoney=ls.get(i).getPurchaseMoney();
			}
			ls.get(i).setPurchaseTypeName(PurchasePlanFlowTypeEnum.getNameByKey(Integer.valueOf(ls.get(i).getPurchaseType())));
			ls.get(i).setPurchaseStartTime(purchaseTypeReqVO.getPurchaseStartTime());
			ls.get(i).setPurchaseEndTime(purchaseTypeReqVO.getPurchaseEndTime());
			lsCopy.add(ls.get(i));
			if(i==ls.size()-1){
				AreaPurchaseTypeVO areaPurchaseTypeVO=new AreaPurchaseTypeVO();
				areaPurchaseTypeVO.setPurchaseTypeName("合计");
				areaPurchaseTypeVO.setPurchaseStartTime(purchaseTypeReqVO.getPurchaseStartTime());
				areaPurchaseTypeVO.setPurchaseEndTime(purchaseTypeReqVO.getPurchaseEndTime());
				areaPurchaseTypeVO.setPurchaseAmount(purchaseAmount);
				areaPurchaseTypeVO.setPurchaseMoney(NumberUtils.seekercentage2Double(purchaseMoney));
				areaPurchaseTypeVO.setRegionalCompanyId(ls.get(i).getRegionalCompanyId());
				areaPurchaseTypeVO.setRegionalCompanyName(ls.get(i).getRegionalCompanyName());
				lsCopy.add(areaPurchaseTypeVO);
			}
		}
		return lsCopy;
	}
	
	
	public RestReturnResult searchDiscussionHistory(DiscussionHistorySearchReqVO reqVO) {
		RestReturnResult restReturnResult = RestReturnResult.success();
		
		try{
			
			PageCode pageCode = new PageCode(reqVO.getPageNumber(), reqVO.getPageSize());
			Map<String, Object> map = new HashMap<String, Object>();
			
			map.put("regionalCompanyId", reqVO.getRegionalCompanyId());
			map.put("launchStartTime", reqVO.getLaunchStartTime());
			map.put("launchEndTime", reqVO.getLaunchEndTime());
			
			pageCode.setCount(specialPurchaseReportMapper.searchDiscussionHistoryCount(map));
			
			map.put("currentRecordNum", (pageCode.getPageNo() - 1) * pageCode.getPageSize());
            map.put("pageSize", pageCode.getPageSize());
            map.put("pageFlag", reqVO.getPageFlag());
            
            List<DiscussionHistorySearchResVO>  list = specialPurchaseReportMapper.searchDiscussionHistory(map);
            pageCode.setList(list);
            
            return new RestReturnResult(CommonConstants.SUCCESS, pageCode);
			
		}catch(Exception e){
			e.printStackTrace();
			logger.error("==============searchDiscussionHistory======e:===="+e.getMessage());
			throw new RuntimeException(e.getMessage(), e.getCause());
		}
	}

	public void exportDiscussionHistory(DiscussionHistorySearchReqVO reqVO, HttpServletResponse response, HttpServletRequest request) {
		try{
			
			String fileName = "专项采购一事一议统计.xlsx";
			
			Map<String, Object> map = new HashMap<String, Object>();
			
			map.put("regionalCompanyId", reqVO.getRegionalCompanyId());
			map.put("launchStartTime", reqVO.getLaunchStartTime());
			map.put("launchEndTime", reqVO.getLaunchEndTime());
			
			new ExportExcel("专项采购一事一议统计", DiscussionHistorySearchResVO.class).setDataList(specialPurchaseReportMapper.searchDiscussionHistory(map))
            .write(request,response, fileName).dispose();
			
		}catch(Exception e){
			e.printStackTrace();
			logger.error("==============exportDiscussionHistory======e:===="+e.getMessage());
			throw new RuntimeException(e.getMessage(), e.getCause());
		}
	}

	public List<AreaPurchaseVariationVO>  areaPurchaseVariation(PurchaseReportReqVO purchaseTypeReqVO){
		List<AreaPurchaseVariationVO> ls=specialPurchaseReportMapper.areaPurchaseVariationSummary(purchaseTypeReqVO);
		return ls;
	}

	public void exportStrategicPurchaseDetail(STDetailSearchReqVO reqVO, HttpServletResponse response, HttpServletRequest request) {

		try{

			String fileName = "战略采购详情统计.xlsx";
			Map<String, Object> map = new HashMap<String, Object>();

			map.put("categoryId", reqVO.getCategoryId());
			map.put("supplierName", reqVO.getSupplierName());
			map.put("purchaseStartTime", reqVO.getPurchaseStartTime());
			map.put("purchaseEndTime", reqVO.getPurchaseEndTime());


			new ExportExcel("战略采购详情统计", STDetailSearchResVO.class).setDataList(specialPurchaseReportMapper.searchStrategicPurchaseDetail(map))
					.write(request,response, fileName).dispose();

		}catch(Exception e){
			e.printStackTrace();
			throw new RuntimeException(e.getMessage(), e.getCause());
		}
    }

	public List<STDetailSearchResVO> searchStrategicDirectDetail(STDetailSearchReqVO reqVO) {
		return specialPurchaseReportMapper.searchStrategicDirectDetail(reqVO);
	}
}


